package com.hh.controller;

import com.hh.config.COSConfig;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author 辉辉 2022/8/16 15:26
 */
@Api(tags = "文件上传的接口")
@RestController
@RequestMapping("/admin/file")
public class FileController {

    @Value("${resources.url}")
    private String host;

    @Value("${spring.application.name}")
    private String serviceName;

    @Resource
    private COSConfig cosConfig;

    @Resource
    private COSClient cosClient;

    @PostMapping("/upload/element")
    @ApiOperation("文件上传的接口")
    public ResponseEntity<String> uploadFile(@RequestParam MultipartFile file) throws IOException {
        try {
            InputStream is = new BufferedInputStream(file.getInputStream());
            String pic = UUID.randomUUID().toString().replace("-", "");
            String picName = file.getOriginalFilename();
            assert picName != null;
            String picType = cosConfig.getPrefix() + pic + picName.substring(picName.lastIndexOf("."));
            ObjectMetadata objectMetadata = new ObjectMetadata();
            //设置流的大小
            objectMetadata.setContentLength(file.getSize());
            PutObjectRequest putObjectRequest = new PutObjectRequest(cosConfig.getBucketName(), picType, is, objectMetadata);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            if (putObjectResult.getETag() != null) {
                return ResponseEntity.ok(cosConfig.getUrl() + "/" + picType);
            }
        } catch (IOException e) {
            //出现文件异常
            return ResponseEntity.badRequest().body("文件异常");
        }
        return ResponseEntity.badRequest().build();
//        if (ObjectUtils.isEmpty(file)) {
//            return ResponseEntity.ok().build();
//        }
//        System.err.println("文件名：" + file.getOriginalFilename());
//        System.err.println("文件大小：" + file.getSize());
//        //保存到本地54
////        String filename = file.getOriginalFilename();
//        String filename = System.currentTimeMillis() + UUID.randomUUID().toString();
//        // 获取后缀
//        String uploadFileName = file.getOriginalFilename();
//        String[] split = uploadFileName.split("\\.");
//        // 后缀
//        String fileType = split[split.length - 1];
//        //设置路径
//        //将id换成文件名，替换掉上次上传的
//        String fullPath = UploadPathConstant.FILE_PATH + filename + "." + fileType;
//        File dest = new File(fullPath);
//        file.transferTo(dest);
//        System.err.println("文件名称：" + filename);
//        System.err.println("上传到：" + dest.getAbsolutePath());
//        return ResponseEntity.ok(host + "/" + serviceName + "/file/" + filename + "." + fileType);
    }

//    @RequestMapping("/download")
//    public String download(String token) throws IOException {
//        int userId = TokenUtil.getUserId(token);
//        System.err.println(userId);
//        String path = "D:\\Users\\富少辉\\Desktop\\springboot+vue\\springboot-vue-shop\\vue\\src\\img\\";
//        FileInputStream fis = new FileInputStream(path + "2.jpg");
//        ByteArrayOutputStream bos = new ByteArrayOutputStream();
//        byte[] bytes = new byte[fis.available()];
//        bos.write(bytes);
//        byte[] fileBytes = bos.toByteArray();
//        //进行base64编码
////        BASE64Encoder encoder = new BASE64Encoder();
//        Base64.Encoder encoder = Base64.getEncoder();
//        String encodeString = encoder.encodeToString(fileBytes);
//        System.err.println("encodeString = " + encodeString);
//        Map<String, String> map = new HashMap<>();
//        map.put("message", "成功");
//        map.put("img", encodeString);
//        return JSON.toJSONString(map);
//    }
}
